const menuTmpl = require("./tmpl/build/template");

require("./sass/menu.scss");
require("metismenu/dist/metisMenu.js");

const INTERVAL = 200; // throttle interval

class Menu {
    constructor(dom, callback) {
        this.container = dom;
        this.render();
        this.callback = callback;
        this.bindEvent();
    }

    render(){
        var html = menuTmpl("menu", {});
        $(this.container).html(html);
        $("#side-menu").metisMenu();
    }
    
    bindEvent() {

        var that = this;
        
        var throttleResize = (function(interval){
            var timeId = null;

            var toggleSidemenu = function(){
                console.log("Resizing");
                var width = (window.innerWidth > 0) ? window.innerWidth : window.screen.width;
                if(width < 768){
                    $("[data-sidemenu]").addClass("collapse");
                }else{
                    $("[data-sidemenu]").removeClass("collapse");
                }
            };

            return function(){
                if (timeId){
                    clearTimeout(timeId);
                }

                timeId = setTimeout(toggleSidemenu, interval);
            };

        })(INTERVAL);

        $(window).on("load resize", throttleResize);
        $(this.container).find("[data-action=change-state]").unbind("click").bind("click", function(){
            if(typeof that.callback === "function"){
                let state = $(this).data("state");
                that.callback(state);
            }
        });
    }
}

export default Menu;